package com.touni.datastructure;

/**
 * @ClassName : DemoStack
 * @Description :
 * @Author : lwq
 * @Date: 2021-04-23 14:41
 */
public class DemoStack<T> {

    //数组
    private Object[] data;

    //数组索引位置 待插入的索引的下标，
    private int index = 0;

    private int size;

    public DemoStack(){
        this.data = new Object[16];
        this.size = 16;
    }

    public DemoStack(int size){
        this.data = new Object[size];
        this.size = size;
    }

    private void reSize(){
        Object[] temp = new Object[size * 2];
        System.arraycopy(data,0,temp,0,size);
        this.size = size *2;
        this.data = temp;
    }

    public boolean push(T value){
        if (index > size){
            reSize();
        }
        data[index] = value;
        index++;
        return Boolean.TRUE;
    }

    public T pop(){
        if (index < 0){
            throw new RuntimeException("stack is empty");
        }
        T value = (T) data[index -1];
        data[index -1] = null; //for gc
        index--;
        return value;
    }

    public T peek(){
        return (T) data[index -1];
    }

}
